#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
网络信息系统通用启动脚本
Network Information System Universal Launcher
支持Windows、Linux、Mac系统，自动检测环境并启动应用
"""

import os
import sys
import subprocess
import platform
import sqlite3
from pathlib import Path
from datetime import datetime

class NetworkSystemLauncher:
    def __init__(self):
        self.python_path = None
        self.system_info = {
            'os': platform.system(),
            'release': platform.release(),
            'machine': platform.machine(),
            'python_version': sys.version
        }
    
    def print_banner(self):
        """打印启动横幅"""
        print("=" * 60)
        print("网络信息系统 - 通用启动器")
        print("Network Information System - Universal Launcher")
        print("=" * 60)
        print(f"操作系统: {self.system_info['os']} {self.system_info['release']}")
        print(f"架构: {self.system_info['machine']}")
        print(f"Python: {self.system_info['python_version'].split()[0]}")
        print("=" * 60)
    
    def find_python_executable(self):
        """自动检测Python可执行文件"""
        # 优先使用当前Python解释器
        current_python = sys.executable
        if current_python and Path(current_python).exists():
            self.python_path = current_python
            print(f"[OK] 使用当前Python: {current_python}")
            return True
        
        # 尝试常见的Python命令
        python_commands = ['python3', 'python', 'py']
        if self.system_info['os'] == 'Windows':
            python_commands = ['python', 'py', 'python3']
        
        for cmd in python_commands:
            try:
                result = subprocess.run([cmd, '--version'], 
                                      capture_output=True, text=True, timeout=10)
                if result.returncode == 0:
                    self.python_path = cmd
                    print(f"[OK] 找到Python: {cmd} ({result.stdout.strip()})")
                    return True
            except:
                continue
        
        print("[ERROR] 未找到Python安装")
        return False
    
    def check_python_version(self):
        """检查Python版本"""
        try:
            result = subprocess.run([self.python_path, '--version'], 
                                  capture_output=True, text=True, timeout=10)
            if result.returncode == 0:
                version_str = result.stdout.strip()
                # 提取版本号
                version_parts = version_str.split()[1].split('.')
                major, minor = int(version_parts[0]), int(version_parts[1])
                
                if major >= 3 and minor >= 7:
                    print(f"[OK] Python版本检查通过: {version_str}")
                    return True
                else:
                    print(f"[ERROR] Python版本过低: {version_str} (需要3.7+)")
                    return False
        except Exception as e:
            print(f"[ERROR] Python版本检查失败: {e}")
            return False
    
    def install_dependencies(self):
        """安装依赖包"""
        requirements_file = Path("requirements.txt")
        if not requirements_file.exists():
            print("[ERROR] 错误: 找不到requirements.txt文件")
            return False
        
        print("[INFO] 正在安装依赖包...")
        try:
            # 先升级pip
            subprocess.check_call([self.python_path, "-m", "pip", "install", "--upgrade", "pip"], 
                                timeout=300)
            
            # 安装依赖包
            subprocess.check_call([self.python_path, "-m", "pip", "install", "-r", "requirements.txt"], 
                                timeout=600)
            print("[OK] 依赖包安装完成")
            return True
        except subprocess.CalledProcessError as e:
            print(f"[ERROR] 依赖包安装失败: {e}")
            print("\n请尝试手动安装:")
            print(f"{self.python_path} -m pip install Flask Flask-SQLAlchemy Flask-Login Flask-WTF Flask-CORS SQLAlchemy WTForms python-dotenv requests psutil schedule")
            return False
        except subprocess.TimeoutExpired:
            print("[ERROR] 安装超时，请检查网络连接")
            return False
    
    def initialize_database(self):
        """初始化数据库"""
        # 确保 instance 目录存在
        instance_dir = Path("instance")
        instance_dir.mkdir(exist_ok=True)
        
        db_path = instance_dir / "network_system.db"
        
        print("[INFO] 正在初始化数据库...")
        
        # 如果数据库文件已存在，先备份
        if db_path.exists():
            backup_path = instance_dir / f"network_system_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.db"
            try:
                db_path.rename(backup_path)
                print(f"[OK] 已备份现有数据库到: {backup_path}")
            except Exception as e:
                print(f"[WARNING] 备份数据库失败: {e}")
        
        try:
            # 创建数据库连接
            conn = sqlite3.connect(str(db_path))
            cursor = conn.cursor()
            
            # 创建用户表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS user (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    username VARCHAR(80) UNIQUE NOT NULL,
                    email VARCHAR(120) UNIQUE NOT NULL,
                    password VARCHAR(120) NOT NULL,
                    role VARCHAR(20) DEFAULT 'recon',
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    last_login_at DATETIME,
                    is_online BOOLEAN DEFAULT 0
                )
            ''')
            
            # 创建用户会话表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS user_session (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    user_id INTEGER NOT NULL,
                    session_token VARCHAR(255) UNIQUE NOT NULL,
                    login_time DATETIME DEFAULT CURRENT_TIMESTAMP,
                    last_activity DATETIME DEFAULT CURRENT_TIMESTAMP,
                    ip_address VARCHAR(45),
                    user_agent TEXT,
                    is_active BOOLEAN DEFAULT 1,
                    FOREIGN KEY (user_id) REFERENCES user (id)
                )
            ''')
            
            # 创建聊天消息表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS chat_message (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    username VARCHAR(80) NOT NULL,
                    text TEXT NOT NULL,
                    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
                )
            ''')
            
            # 创建侦察数据表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS recon_data (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    title VARCHAR(200) NOT NULL,
                    target_system VARCHAR(100) NOT NULL,
                    data_type VARCHAR(50) NOT NULL,
                    content TEXT NOT NULL,
                    priority VARCHAR(20) DEFAULT 'medium',
                    status VARCHAR(20) DEFAULT 'pending',
                    created_by INTEGER,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (created_by) REFERENCES user (id)
                )
            ''')
            
            # 创建分析结果表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS analysis_result (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    recon_data_id INTEGER,
                    analysis_type VARCHAR(50) NOT NULL,
                    findings TEXT NOT NULL,
                    recommendations TEXT NOT NULL,
                    priority_targets TEXT,
                    suggested_actions TEXT,
                    confidence_level VARCHAR(20) DEFAULT 'medium',
                    status VARCHAR(20) DEFAULT 'pending',
                    created_by INTEGER,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (recon_data_id) REFERENCES recon_data (id),
                    FOREIGN KEY (created_by) REFERENCES user (id)
                )
            ''')
            
            # 创建决策指令表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS decision_order (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    analysis_id INTEGER,
                    order_type VARCHAR(50) NOT NULL,
                    target VARCHAR(200) NOT NULL,
                    objective TEXT NOT NULL,
                    instructions TEXT NOT NULL,
                    priority VARCHAR(20) DEFAULT 'medium',
                    deadline DATETIME,
                    status VARCHAR(20) DEFAULT 'pending',
                    assigned_to INTEGER,
                    created_by INTEGER,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (analysis_id) REFERENCES analysis_result (id),
                    FOREIGN KEY (assigned_to) REFERENCES user (id),
                    FOREIGN KEY (created_by) REFERENCES user (id)
                )
            ''')
            
            # 创建执行结果表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS execution_result (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    order_id INTEGER,
                    result_type VARCHAR(50) NOT NULL,
                    description TEXT NOT NULL,
                    evidence TEXT,
                    impact_assessment TEXT,
                    lessons_learned TEXT,
                    status VARCHAR(20) DEFAULT 'pending',
                    created_by INTEGER,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (order_id) REFERENCES decision_order (id),
                    FOREIGN KEY (created_by) REFERENCES user (id)
                )
            ''')
            
            # 创建系统日志表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS system_log (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
                    level VARCHAR(20) NOT NULL,
                    message TEXT NOT NULL,
                    user_id INTEGER,
                    action_type VARCHAR(50),
                    FOREIGN KEY (user_id) REFERENCES user (id)
                )
            ''')
            
            # 创建默认用户
            default_users = [
                # ('recon1', 'recon1@example.com', 'recon123', 'recon'),
                # ('analyst1', 'analyst1@example.com', 'analyst123', 'analyst'),
                # ('decision1', 'decision1@example.com', 'decision123', 'decision'),
                # ('executor1', 'executor1@example.com', 'executor123', 'executor'),
                ('lyh', 'lyh@example.com', 'lyh', 'recon'),
                ('xcw', 'xcw@example.com', 'xcw', 'recon'),
                ('gjh', 'gjh@example.com', 'gjh', 'recon'),
                ('shx', 'shx@example.com', 'shx', 'recon'),
                ('zzj', 'zzj@example.com', 'zzj', 'recon'),

            ]
            
            for username, email, password, role in default_users:
                cursor.execute('''
                    INSERT OR IGNORE INTO user (username, email, password, role)
                    VALUES (?, ?, ?, ?)
                ''', (username, email, password, role))
            
            # 提交更改
            conn.commit()
            conn.close()
            
            print("[OK] 数据库初始化成功")
            print("[OK] 默认用户账户已创建:")
            # print("   侦察员: recon1 / recon123")
            # print("   分析员: analyst1 / analyst123")
            # print("   决策员: decision1 / decision123")
            # print("   执行员: executor1 / executor123")
            
            # 设置文件权限（Unix系统）
            if os.name != 'nt':  # 非Windows系统
                try:
                    os.chmod(db_path, 0o664)
                    print("[OK] 数据库文件权限设置完成")
                except Exception as e:
                    print(f"[WARNING] 权限设置失败: {e}")
            
            return True
            
        except Exception as e:
            print(f"[ERROR] 数据库初始化失败: {e}")
            return False
    
    def test_database(self):
        """测试数据库连接"""
        try:
            conn = sqlite3.connect("instance/network_system.db")
            cursor = conn.cursor()
            cursor.execute("SELECT COUNT(*) FROM user")
            user_count = cursor.fetchone()[0]
            conn.close()
            
            print(f"[OK] 数据库连接测试成功，用户数量: {user_count}")
            return True
        except Exception as e:
            print(f"[ERROR] 数据库连接测试失败: {e}")
            return False
    
    def start_application(self):
        """启动应用程序"""
        print("\n[INFO] 正在启动网络信息系统...")
        print("=" * 50)
        print("系统信息:")
        print("- 访问地址: http://localhost:5000")
        print("- 默认账户: admin / admin123")
        print("- 按 Ctrl+C 停止服务")
        print("=" * 50)
        
        try:
            # 检查app.py是否存在
            if not Path("app.py").exists():
                print("[ERROR] 找不到应用程序文件: app.py")
                return False
            
            # 启动应用程序
            subprocess.run([self.python_path, "app.py"])
            return True
            
        except KeyboardInterrupt:
            print("\n[INFO] 系统已停止")
            return True
        except FileNotFoundError:
            print(f"[ERROR] 找不到应用程序文件: app.py")
            return False
        except Exception as e:
            print(f"[ERROR] 启动失败: {e}")
            return False
    
    def run(self):
        """运行启动器"""
        self.print_banner()
        
        # 1. 检测Python环境
        if not self.find_python_executable():
            self.print_install_instructions()
            return False
        
        # 2. 检查Python版本
        if not self.check_python_version():
            return False
        
        # 3. 安装依赖
        if not self.install_dependencies():
            return False
        
        # 4. 初始化数据库
        if not self.initialize_database():
            return False
        
        # 5. 测试数据库
        if not self.test_database():
            return False
        
        # 6. 启动应用
        return self.start_application()
    
    def print_install_instructions(self):
        """打印安装说明"""
        print("\n📋 Python安装说明:")
        print("=" * 40)
        
        if self.system_info['os'] == 'Windows':
            print("Windows系统:")
            print("1. 访问 https://www.python.org/downloads/")
            print("2. 下载Python 3.7或更高版本")
            print("3. 安装时勾选 'Add Python to PATH'")
            print("4. 重新运行此脚本")
        elif self.system_info['os'] == 'Darwin':  # macOS
            print("macOS系统:")
            print("1. 使用Homebrew: brew install python3")
            print("2. 或访问 https://www.python.org/downloads/")
            print("3. 重新运行此脚本")
        else:  # Linux
            print("Linux系统:")
            print("Ubuntu/Debian: sudo apt install python3 python3-pip")
            print("CentOS/RHEL: sudo yum install python3 python3-pip")
            print("Arch Linux: sudo pacman -S python python-pip")
            print("重新运行此脚本")

def main():
    """主函数"""
    launcher = NetworkSystemLauncher()
    success = launcher.run()
    
    if not success:
        print("\n[ERROR] 启动失败，请检查错误信息")
        input("按回车键退出...")
        sys.exit(1)

if __name__ == "__main__":
    main()
